<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customers_model extends MY_Model {

	function __construct()
	{
		parent:: __construct();
		$this->table = "km_customers";
		$this->object = "CustObj";
	}

	function login($username, $password)
	{
        $query = $this->db->get_where($this->table, array("username"=>$username));
        if($query->num_rows()==0)
		{
			$data['error'] = "Username wrong";
		}
		else
		{
            $user = $query->row_array();
			$salt = $user['salt'];
			$db_pwd = $user['pwd'];
			if(md5($password.$salt) == $db_pwd)   //the password is correct
			{
               $data['user'] = $user;
			}
			else
			{
				$data['error'] = "Password wrong";
			}
		}
		return $data;
	}

	function change_password($username, $new_password, $salt)
	{
    	$pwd = md5($new_password . $salt);
		if($this->db->update($this->table, array("pwd"=>$pwd), array("username"=>$username)))
		{
			$data['success'] = "Password changed successfully";
		}
		else{
			$data['error'] = $this->util->handle_error();
		}
		return $data;

	}

	function register_customer()
	{
        $customer = new CustObj();
		$customer->set_vars();
        $customer->reg_date =date("Y-m-d h:i:s");
		$customer->salt = hash("SHA1", uniqid(rand(), true));
        $customer->pwd =md5($customer->pwd . $customer->salt);

		if($this->db->insert($this->table, $customer))
		{
			$data['success'] = "Registration successfully";
		}
		else{
			$data['error'] = $this->util->handle_error();
		}
		return $data;
	}

	function update_profile($username)
	{
        $customer = new CustObj();
        //removing some fields from customer object
		unset($customer->username);
		unset($customer->pwd);
		unset($customer->salt);
		unset($customer->reg_date);
        //collect data from post
		$customer->set_vars();

		if($this->db->update($this->table,$customer, array("username"=>$username)))
		{
			$data['success'] = "Profile updated sucessfully";
        }
		else
		{
			$data['error'] = $this->util->handle_error();
		}
		return $data;

	}


}

class CustObj extends ObjectModel
{
	//cust_id

	public $title="";
	public $surname = "";
	public $firstname = "";
	public $middlename = "";
	public $address = "";
	public $city = "";
	public $state = "";
	public $country = "";
	public $phone = "";
	public $cellphone = "";
	public $email = "";

	public $username = "";
	public $pwd = "";
	public $salt = "";
	public $reg_date = "";
			
}